package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.threadlocal.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

  @Autowired
  private WmNewsMaterialMapper wmNewsMaterialMapper;

  @Autowired
  private WmMaterialMapper wmMaterialMapper;

  @Autowired
  private WmNewsTaskService wmNewsTaskService;

  @Autowired
  private RabbitTemplate rabbitTemplate;
  @Autowired
  private WmAutoScanServiceImpl wmAutoScanService;

  /**
   * 查询文章列表
   *
   * @param dto
   * @return
   */
  @Override
  public ResponseResult list(WmNewsPageReqDto dto) {
    //1.非空判断
    dto.checkParam();
    //2.分页查询
    IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
    LambdaQueryWrapper<WmNews> queryWrapper = Wrappers.lambdaQuery();
    //2.1 根据状态查询
    if (dto.getStatus() != null) {
      queryWrapper.eq(WmNews::getStatus, dto.getStatus());
    }

    //2.2 根据关键字查询
    if (!StringUtils.isEmpty(dto.getKeyword())) {
      queryWrapper.like(WmNews::getTitle, dto.getKeyword());
    }

    //2.3 根据频道id查询
    if (dto.getChannelId() != null) {
      queryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
    }

    //2.4 根据开始和结束时间查询
    if (dto.getBeginPubdate() != null && dto.getEndPubdate() != null) {
      queryWrapper.between(WmNews::getPublishTime, dto.getBeginPubdate(), dto.getEndPubdate());
    }

    //2.5 根据登录用户id查询
    queryWrapper.eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId());

    page = super.page(page, queryWrapper);

    //3.返回数据结果
    ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
    result.setData(page.getRecords());
    return result;
  }

  /**
   * 保存-修改-提交草稿为一体的方法
   * 主方法
   *
   * @param dto
   * @return
   */
  @Override
  public ResponseResult submit(WmNewsDto dto) {
    //TODO
    //条件判断
    if (dto == null || dto.getContent() == null) {
      return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }
    //保存或修改文章
    WmNews wmNews = new WmNews();
    //属性的拷贝只有属性名词和类型相同才能拷贝
    BeanUtils.copyProperties(dto, wmNews);
    //封面图片list->string
    if (dto.getImages() != null && dto.getImages().size() > 0) {
      String imageStr = StringUtils.join(dto.getImages(), ",");
      wmNews.setImages(imageStr);
    }
    //如果当前封面类型为自动
    if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
      wmNews.setType(null);
    }
    saveOrUpdateWmNews(wmNews);
    //判断是否为草稿
    if (dto.getStatus().equals(WmNews.Status.NORMAL.getCode())) {
      //如果为草稿，结束当前方法
      return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
    //不是草稿，保存文章内容图片与素材的关系
    //获取到文章内容中的图片信息
    List<String> materials = ectracUrlInfo(dto.getContent());
    saveRelativeInfoForContent(materials, wmNews.getId());
    //如果当前布局是自动，需要匹配封面图片
    saveRelativeInForCover(dto, wmNews, materials);
    //审核文章
    try {
      wmAutoScanService.autoScanWmNews(wmNews.getId());
    } catch (Exception e) {
      e.printStackTrace();
    }
    //6.返回结果数据
    return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
  }

  //处理文章内容图片与素材的关系
  private void saveRelativeInfoForContent(List<String> materials, Integer id) {
    saveRelativeInfo(materials, id, WemediaConstants.WM_CONTENT_REFERENCE);
  }

  private void saveRelativeInfo(List<String> materials, Integer id, Short type) {
    if (materials != null && !materials.isEmpty()) {
      //通过图片的url查询素材的id
      List<WmMaterial> dbMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materials));
      //判断素材是否有效
      if (dbMaterials == null || dbMaterials.size() == 0) {
        //手动抛出异常第一个功能：能够提示调用者素材失效，第二个功能，进行数据的回滚
        throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
      }
      List<Integer> idList = dbMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
      //批量保存

      wmNewsMaterialMapper.saveRelations(idList, id, type);
    }
  }

  private void saveRelativeInForCover(WmNewsDto dto, WmNews wmNews, List<String> materials) {
    List<String> images = materials.stream().limit(3).collect(Collectors.toList());
    //如果当前封面为自动则设置当前封面类型的数据
    if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
      //多图
      if (materials.size() >= 3) {
        wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
        images = materials.stream().limit(3).collect(Collectors.toList());
        String join = String.join(",", images);
        wmNews.setImages(join);
      } else if (
          materials.size() >= 1 && materials.size() < 3) {
        //单图
        wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
        wmNews.setImages(images.get(0));
      } else {
        //无图
        wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
      }
      //修改文章
      if (images != null && images.size() > 0) {
        wmNews.setImages(StringUtils.join(images, ","));
      }
      updateById(wmNews);
    }
    if (images != null && images.size() > 0) {
      saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_COVER_REFERENCE);
    }
  }

  private List<String> ectracUrlInfo(String content) {
    List<String> materials = new ArrayList<>();
//    List<Map> maps = JSON.parseArray(content, Map.class);
    /*for (Map map : maps) {
      if (map.get("type").equals("image")) {
        String imgUrl = (String) map.get("value");
        materials.add(imgUrl);
      }
    }*/
    JSONArray parse = (JSONArray) JSONArray.parse(content);
    for (int i = 0; i < parse.size(); i++) {
      JSONObject obj = (JSONObject) parse.get(i);
      if (obj.getString("type").equals("image")) {
        materials.add((String) obj.getString("value"));
      }
    }
    return materials;
  }

  @Autowired
  private WmNewsMaterialMapper WmNewsMaterialMapper;

  //保存或修改文章
  private void saveOrUpdateWmNews(WmNews wmNews) {
//补全属性
    wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
    wmNews.setCreatedTime(new Date());
    wmNews.setSubmitedTime(new Date());
    wmNews.setEnable((short) 1);//默认上架
    if (wmNews.getId() == null) {
      //保存
      save(wmNews);
    } else {
      //修改
      //删除文章图片与素材的关系
      wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
      updateById(wmNews);
    }

  }

  /**
   * 文章上下架
   *
   * @param dto
   * @return
   */
  @Override
  public ResponseResult downOrUp(WmNewsDto dto) {
    //TODO
    //1、检查参数
    if (dto.getId() == null) {
      return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }
    //2、查询文章
    WmNews wmNews = getById(dto.getId());
    if (wmNews == null) {
      return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
    }
    //3、判断文章是否发布
    if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
      return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }
    //4、修改文章
    if (dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2) {
      update(Wrappers.<WmNews>lambdaUpdate().set(WmNews::getEnable, dto.getEnable())
          .eq(WmNews::getId, wmNews.getId()));
    }

    return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
  }
}
